package com.server.http.handler.impl;

import com.server.conditionenum.HttpReturnStatus;
import com.server.db.DataBaseManager;
import com.server.http.handler.HttpHandler;
import com.server.http.request.HttpRequestMessage;
import com.server.http.response.HttpResponseMessage;
import com.server.mine.net.HttpProtocol;
import com.server.tools.EncryptionTools;

/**
 * @author 李小布
 * @date 2018年4月20日 下午5:29:32
 * @version 1.0
*/
public class AddAccount extends HttpHandler{
	@Override
	public void handle(HttpRequestMessage request, HttpResponseMessage response) {
		int status = 0;
		String failMsg = null;
		
		String uname = request.getParameter("uname");
		String password = request.getParameter("password");
		int power = 0;
		try {
			power = Integer.parseInt(request.getParameter("power"));
		}catch (Exception e) {
			power = -1;
		}
		
		if(uname == "" || password == "" || power == -1) {
			failMsg = "参数错误或参数值为空！";
		}else if(uname.length() > 16){
			failMsg = "请确保帐号长度小于等于16位！";
		}
		else if(uname.length() < 2){
			failMsg = "请确保帐号长度大于2位！";
		}
		else {
			try {
				//检测是否存在
				int st = DataBaseManager.GetInstance().JudgeAccountExisted(uname);
				switch (st) {
				case 0:
					if(DataBaseManager.GetInstance().AddAccount(uname, EncryptionTools.MD5(password), power)) {
						status = 1;
					}
					break;
				case 1:
					failMsg = "账户已存在！";
					break;
				default:
					failMsg = "未知错误！";
					break;
				}
				
			} catch (Exception e) {
				e.printStackTrace();
				failMsg = e.getMessage();
			}
		}
		
		if(status == 1) {
			SetReturnData(response,"创建成功",HttpProtocol.ADDACCOUNT,HttpReturnStatus.Successed);
		}else {
			SetReturnData(response,failMsg,HttpProtocol.ADDACCOUNT,HttpReturnStatus.Failed);
		}
	}
}
